//boost::asio 客户端同步方式通信
//原文链接：https://llfc.club/category?catid=225RaiVNI8pFDD5L4m807g7ZwmF#!aid/2Nr3U2vU2UxYM0odYRGAk3wWO1S

#include <cstdint>
#include <iostream>
#include <string.h>
#include <utility>
#include <memory>
#include <boost/asio.hpp>

#include "../log.h"

constexpr uint32_t MAX_LEN = 1024;

int main(void)
{
    using namespace boost::asio::ip;

    try
    {
        //创建上下文服务
        boost::asio::io_context ioc;
        //构造服务器endpoint
        tcp::endpoint ep(address::from_string("127.0.0.1"), 8080);
        //创建本地socket
        tcp::socket socket(ioc);
        //链接服务器
        boost::system::error_code error = boost::asio::error::host_not_found;
        socket.connect(ep, error);
        if(error)
        {
            log_error("connect error, error code: {}, error message: {}", error.value(), error.message());
            return -1;
        }
        log_debug("local ip: {}, local port: {}", socket.local_endpoint().address().to_string(), socket.local_endpoint().port());
        
        while(true)
        {
            //发送数据
            std::cout << "please input your message: ";
            char request[MAX_LEN];
            std::cin.getline(request, MAX_LEN);
            uint32_t len = strlen(request);
            int ret = boost::asio::write(socket, boost::asio::buffer(request, len));
            if(ret <= 0)
            {
                log_error("write error, ret: {}", ret);
                return -1;
            }

            std::unique_ptr<char[]> p(new char[MAX_LEN]);
            memset(p.get(), 0, MAX_LEN);
            ret = boost::asio::read(socket, boost::asio::buffer(p.get(), len));
            if(ret <= 0)
            {
                log_error("read error, ret: {}", ret);
                return -1;
            }
            log_info("reply is: {}", p.get());
        }
    }
    catch (const std::exception& e)
    {
        log_error("Exception: ", e.what());
    }

    return 0;
}